﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using ttg_internal.Utilities.Common.Other;
using ttg_internal.Utilities.UsageVisualizer.View;
using ttg_internal.utils;

namespace ttg_internal.Utilities.UsageVisualizer.ViewModel
{
    /// <summary>
    /// Model for <see cref="MainView" />
    /// </summary>
    internal class MainViewModel : BindableObject
    {
        /// <summary>
        /// Inititalizes a new instance visualizing devices from the specified global information
        /// </summary>
        public MainViewModel(GlobalInfo globalInfo)
        {
            DeviceUsageTabs = new ObservableCollection<DeviceUsageTabViewModel>();
            GlobalUsageTabs = new ObservableCollection<GlobalUsageTabViewModel> { new GlobalUsageTabViewModel(globalInfo) };

            globalInfo.Devices.ListChanged += OnDevicesListChanged;
            OnDevicesListChanged(globalInfo.Devices, new ListChangedEventArgs(ListChangedType.Reset, -1));
        }

        /// <summary>
        /// Global usage tabs
        /// </summary>
        public ObservableCollection<GlobalUsageTabViewModel> GlobalUsageTabs { get; private set; }

        /// <summary>
        /// List of all usage tabs
        /// </summary>
        public ObservableCollection<DeviceUsageTabViewModel> DeviceUsageTabs { get; private set; }

        /// <summary>
        /// Processes device list change
        /// </summary>
        private void OnDevicesListChanged(object sender, ListChangedEventArgs e)
        {
            Debug.Assert(sender is IList<DeviceInfo>);
            var senderList = (IList<DeviceInfo>)sender;

            switch (e.ListChangedType)
            {
                case ListChangedType.Reset:
                    DeviceUsageTabs.Clear();

                    foreach (DeviceInfo info in senderList)
                    {
                        DeviceUsageTabs.Add(new DeviceUsageTabViewModel(info));
                    }

                    break;

                case ListChangedType.ItemAdded:
                    DeviceUsageTabs.Add(new DeviceUsageTabViewModel(senderList[e.NewIndex]));
                    break;

                case ListChangedType.ItemChanged:
                    break;

                default:
                    throw new NotSupportedException();
            }
        }
    }
}


